/*
 * @Descripttion:
 * @Author: liuyu
 * @Date: 2023-12-04 15:44:23
 * @LastEditors: liuyu
 * @LastEditTime: 2023-12-04 15:44:23
 * @FilePath: /app/controller/role.js
 */
'use strict';

const Controller = require('egg').Controller;
class RoleController extends Controller {
  async show() {
    const { ctx: { service, params } } = this;
    const res = await service.role.show({ role_id: params.id });
    const menus = await service.role.menuids(res.role_id);
    // helper.render(200, {
    //   data: res,
    // });
    this.ctx.body = {
      data: {
        ...res,
        menus,
      },
    };
  }
  async list() {
    const { ctx } = this;
    const { page = 1, page_size = 10, ...where } = ctx.query;
    console.log(page, page_size, where);
    if (where.name) {
      where.name = {
        op: 'LIKE',
        value: `'%${where.name}%'`,
      };
    }
    where.bid = ctx.locals.auth.userAdminBid;
    console.log(where);
    const res = await ctx.service.shop.product.index([], {
      ...where,
    }, page, page_size);
    ctx.helper.render(200, {
      data: res.res,
      total: res.count.length,
    });
    // const res = await ctx.service.role.index([], where, page, page_size);
    // const total = await this.app.mysql.get('db1').count('role', {
    //   ...where,
    // });
    // ctx.helper.render(200, {
    //   data: res,
    //   total,
    // });
  }
  async create() {
    const { ctx: { service, helper, request } } = this;
    const body = request.body;
    // const userInfo = await service.userAdmin.show({ id: ctx.locals.auth.userAdminBid });
    const showRes = await service.role.show({ role_name: body.role_name });
    if (showRes) {
      helper.render(422, {}, '角色名称已存在');
      return;
    }
    try {
      await service.role.create(body);
      helper.render(200, {}, '添加成功');
    } catch (e) {
      helper.render(422, e, '添加失败');
    }
  }
  async update() {
    const { ctx: { service, helper, params, request } } = this;
    const body = request.body;
    const where = { role_id: params.id };
    delete body.create_by;
    delete body.create_time;
    try {
      await service.role.update(body, where);
      helper.render(200, {}, '更新成功');
    } catch (e) {
      helper.render(422, e, '更新失败');
    }
  }
  async delete() {
    const { ctx: { service, helper, params } } = this;
    try {
      await service.role.delete(params.id);
      helper.render(200, {}, '删除成功');
    } catch (e) {
      helper.render(422, e, '删除失败');
    }
  }
}

module.exports = RoleController;
